const url = 'https://movie.douban.com/tag/#/?sort=R&range=0,10&tags=';

const puppeteer = require('puppeteer');
// const path = require('path');

const sleep = time => new Promise(resolve => setTimeout(resolve, time));

(async () => {
  try {
    console.log('Start visit the target page')
    const browser = await puppeteer.launch({
      // headless: false
    });
    const page = await browser.newPage();
    await page.goto(url, {
      timeout: 300000,
      waitUntil: 'networkidle2'
    });
    await sleep(3000);
    await page.waitForSelector('.more');
    for (let i = 0; i < 1; i++) {
      await sleep(3000)
      await page.click('.more')
    }
    const result = await page.evaluate(() => {
      const $ = window.$;
      const items = $('.list-wp a');
      const links = [];
      if (items.length >= 1) {
        items.each((index, item) => {
          let it = $(item);
          let doubanId = it.find('div').data('id');
          let title = it.find('.title').text();
          let rate = Number(it.find('.rate').text());
          let poster = it.find('img').attr('src').replace('s_ratio_poster', 'l_ratio_poster');
          links.push({
            doubanId,
            title,
            rate,
            poster
          });
        });
      }
      return links;
    })
    await browser.close();

    process.send({
      result
    });
    process.exit(0);

  } catch (error) {
    console.log(`错误${error}`);
  }
})();